<template>
  <div class="wrapper-add-edit">
    <div class="wrapper-form">
      <el-form ref="refForm" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="所属栏目">
          <el-tree-select
            v-model="formData.idCategory"
            :data="treeSelectData"
            :props="{ value: 'id', label: 'label' }"
            :render-after-expand="false"
            :current-node-key="0"
            value-key="id"
            placeholder="选择所属栏目"
            check-strictly
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item label="文章属性">
          <el-checkbox-group v-model="symbolShows" @change="onSymbolShowChange">
            <el-checkbox v-for="item in symbolShowOptions" :key="item.id" :label="item.lable" :value="item.id" />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="跳转链接">
          <el-input ref="refJumpUrl" v-model="formData.urlJump" maxlength="300" show-word-limit />
        </el-form-item>

        <el-form-item label="标签">
          <el-input v-model="formData.tag" maxlength="100" placeholder="多个标签以半角英文 , 分隔" />
        </el-form-item>

        <el-form-item label="主标题" prop="title">
          <el-input v-model="formData.title" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="短标题">
          <el-input v-model="formData.titleShort" maxlength="20" show-word-limit />
        </el-form-item>

        <el-form-item label="引题">
          <el-input v-model="formData.titleHead" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="副标题">
          <el-input v-model="formData.titleSub" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="标题图">
          <TheUploaderImage @setUploadResult="getUploadResult($event)" />
        </el-form-item>

        <el-form-item label="正文内容">
          <Tinymce6 :content="formData.content" @inputContent="getContent" />
        </el-form-item>

        <el-form-item label="文章简介">
          <el-input v-model="formData.intro" :rows="6" type="textarea" maxlength="140" show-word-limit />
        </el-form-item>

        <el-form-item label="来源">
          <el-input v-model="formData.source" maxlength="30" placeholder="例：新华社微信公众号" />
        </el-form-item>

        <el-form-item label="作者">
          <el-input v-model="formData.author" maxlength="20" />
        </el-form-item>

        <el-form-item label="发布时间">
          <el-date-picker
            v-model="formData.dtPublish"
            type="datetime"
            placeholder="选择文章发布日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onAdd2Draft()">存为草稿</el-button>
          <el-button type="primary" @click="onSubmit()">保存并提交审核</el-button>
          <el-button @click="onBack2List()">取消并返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { getAdminId } from '@/utils/common'
import { obj2Str } from '@/utils/datetime'
import { AryToTree, IsAryContainVal } from '@/utils/array'
import { toastSuccess, toastError } from '@/utils/toast'
import { getLStorageObj } from '@/utils/web-storage'

import Tinymce6 from '@c/Tinymce6'
import TheUploaderImage from '@c/UploadImage2Local'

import router from '@/router'
import store from '@/store'
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
  name: 'ArticleAddView',
  components: { Tinymce6, TheUploaderImage },
  setup() {
    const formData = ref({
      id: 0,
      idCategory: 2,
      idUnit: 0,
      idDepartment: 0,
      symbolShow: '',
      source: '',
      // 文章状态： 0：草稿 1：删除 2：待审 3：已审待签发 4：已签发 5：已生成静态文件
      status: '0',
      author: '',
      idEditor: 0,
      idChecker: 0,
      idSigner: 0,
      tag: '',
      title: '',
      titleHead: '',
      titleSub: '',
      titleShort: '',
      // 标题图不仅仅有图像的 url ，还有 uuid，因此这里存的是一个对象
      urlTitlePic: '',
      urlTitleVideo: '',
      urlJump: '',
      content: '',
      intro: '',
      dtCreate: obj2Str(new Date()),
      dtPublish: obj2Str(new Date()),
      flagDeleted: 0,
      weight: 1,
      click: 0,
    })
    const rules = ref({
      title: [
        { required: true, message: '标题不能为空！', trigger: 'blur' },
        { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' },
      ],
    })
    const symbolShows = ref([])
    const symbolShowOptions = ref([
      { id: 'a', lable: '特荐' },
      { id: 'b', lable: '加粗' },
      { id: 'c', lable: '推荐' },
      { id: 'f', lable: '幻灯' },
      { id: 'h', lable: '头条' },
      { id: 'j', lable: '跳转' },
      { id: 'p', lable: '图片' },
      { id: 's', lable: '滚动' },
    ])
    const treeSelectData = ref([])
    const refForm = ref(null)
    const refJumpUrl = ref(null)
    const refTinymce = ref(null)

    const getIdAdmin = () => {
      formData.value.idEditor = getAdminId()
    }
    const onBack2List = () => {
      router.push({ path: 'list-page-editor' })
    }
    // 得到所有文章分类
    const listCategory = () => {
      treeSelectData.value = AryToTree(getLStorageObj('AllCategory'), 2)
    }
    // 设置文章属性复选框的值发生变化时
    const onSymbolShowChange = (val) => {
      // 如果填了跳转链接，则 refJumpUrl 的内容为空
      if (val.indexOf('j') >= 0) {
        refJumpUrl.value.focus()
      } else {
        formData.value.urlJump = ''
      }
    }
    // 设置标题图url
    const getUploadResult = (val) => {
      if (val && val !== '') {
        formData.value.urlTitlePic = JSON.stringify(val)
      } else {
        formData.value.urlTitlePic = ''
      }
    }
    // 获取tinymce内容
    const getContent = (val) => {
      formData.value.content = val
    }
    // 保存文章为草稿 文章状态： 0：草稿 1：删除 2：待审 3：已审待签发 4：已签发 5：已生成静态文件
    const onAdd2Draft = () => {
      if (onCheck('0')) {
        onSave2DB('存为草稿成功！')
      }
    }
    // 保存并提交审核
    const onSubmit = () => {
      if (onCheck('2')) {
        onSave2DB('保存成功并已提交审核！')
      }
    }
    // 文章保存前检查相关值
    const onCheck = (status) => {
      // 检查栏目
      if (formData.value.idCategory == 2) {
        toastError('请选择文章所属栏目')
        return false
      }
      // 检查跳转链接
      if (IsAryContainVal(symbolShows.value, 'j') && formData.value.urlJump === '') {
        toastError('请设置跳转链接！')
        refJumpUrl.value.focus()
        return false
      }
      // 将symbolShow数组转为字符串
      formData.value.symbolShow = symbolShows.value.join(',')
      // 文章状态： 0：草稿 1：删除 2：待审 3：已审待签发 4：已签发 5：已生成静态文件
      formData.value.status = status
      return true
    }
    // 文章保存到数据库
    const onSave2DB = (message) => {
      // 验证表单后添加文章
      refForm.value.validate((valid) => {
        if (!valid) {
          toastError('表单验证未通过！请检查您的输入！')
          return false
        }
        store
          .dispatch('article/add', formData.value)
          .then(() => {
            toastSuccess(message)
            onBack2List()
          })
          .catch(() => {})
      })
    }

    onMounted(() => {
      getIdAdmin()
      listCategory()
    })

    return {
      formData,
      rules,
      symbolShows,
      symbolShowOptions,
      treeSelectData,
      refForm,
      refJumpUrl,
      refTinymce,
      getIdAdmin,
      onBack2List,
      onSymbolShowChange,
      listCategory,
      getUploadResult,
      getContent,
      onAdd2Draft,
      onSubmit,
      onCheck,
      onSave2DB,
    }
  },
})
</script>

<style lang="scss" scoped></style>
